<template>
    <div>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="测试题管理">
          <el-input v-model="queryForm.kw" placeholder="关键字" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
  
      <el-table v-loading="loading" :data="list">
        <el-table-column align="center" prop="content" label="题干" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="选项" align="center" prop="optionA" >
          <template #default="scope">
            <div>
              <span v-if="scope.row.optionA">A、{{ scope.row.optionA }} </span>
              <span v-if="scope.row.optionB"> B、{{ scope.row.optionB }}</span>
            </div>
            <div>
              <span v-if="scope.row.optionC">C、{{ scope.row.optionC }} </span>
              <span v-if="scope.row.optionD"> D、{{ scope.row.optionD }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" >
          <template #default="scope">
              <div>{{timestampToDayHM(scope.row.updateTime)}}</div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" sortable prop="floor" label="最后更新">
          <template slot-scope="scope">
            <div>{{scope.row.lastUpdate|timestampToTime}}</div>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="操作" width="280">
          <template #default="scope">
            <el-button link type="success" icon="Document" @click="showDetail(scope.row)">详情</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row.id)">修改</el-button>
            <el-button link type="danger" icon="Close" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <el-pagination background layout="prev, pager, next" v-model:page-size="queryForm.pageSize" v-model:current-page="queryForm.pageNo" :total="total" @current-change="getList" />
      <!-- 添加或修改题目对话框 -->
      <el-dialog v-model="open" :title="title" width="800px" append-to-body>
        <el-form label-width="120px" :model="editForm" :rules="rules" ref="formRef">
          <el-form-item label="题干" prop="content">
            <el-input
              v-model="editForm.content"
              type="textarea"
              :rows="3"
              placeholder="请输入题目的题干"
            ></el-input>
          </el-form-item>
          <el-form-item label="选项A" prop="optionA">
            <el-input
              v-model="editForm.optionA"
              auto-complete="off"
              placeholder=''
            ></el-input>
          </el-form-item>
          <el-form-item label="选项B" prop="optionB">
            <el-input
              v-model="editForm.optionB"
              auto-complete="off"
              placeholder=''
            ></el-input>
          </el-form-item>
          <el-form-item label="选项C" prop="optionC">
            <el-input
              v-model="editForm.optionC"
              auto-complete="off"
              placeholder=''
            ></el-input>
          </el-form-item>
         
          <el-form-item label="选项D" prop="optionD">
            <el-input
              v-model="editForm.optionD"
              auto-complete="off"
              placeholder=''
            ></el-input>
          </el-form-item>
          <el-form-item label="正确选项" prop="correctAns">
            <el-select v-model="editForm.correctAns" placeholder="请选择">
              <el-option
                v-for="item in optionList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!--详情对话框-->
    <el-dialog v-model="openDetail" title="题目详情" width="60%" append-to-body v-if="detailData">
      <el-descriptions class="margin-top" :column="1" border>
          <el-descriptions-item label="题干" labelStyle="width: 160px;">{{ detailData.content }}</el-descriptions-item>
          <el-descriptions-item label="选项A" labelStyle="width: 160px;">{{ detailData.optionA }}</el-descriptions-item>
          <el-descriptions-item label="选项B" labelStyle="width: 160px;">{{ detailData.optionB }}</el-descriptions-item>
          <el-descriptions-item label="选项C" labelStyle="width: 160px;">{{ detailData.optionC }}</el-descriptions-item>
          <el-descriptions-item label="选项D" labelStyle="width: 160px;">{{ detailData.optionD }}</el-descriptions-item>
          <el-descriptions-item label="正确答案" labelStyle="width: 160px;">{{ detailData.correctAns }}</el-descriptions-item>
          
          <!-- <el-descriptions-item label="标签">
          <el-optionB >{{ detailData.productTags }}</el-optionB>
          </el-descriptions-item> -->
          <!-- <el-descriptions-item label="模板正文" labelStyle="width: 160px;">{{ detailData.ruleContent }}</el-descriptions-item> -->
      </el-descriptions>
    </el-dialog>
    </div>
  </template>
  <script setup lang="ts">
  import { ref, reactive, nextTick, toRef } from "vue";
  import baseService from "@/service/baseService";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
  import { fileUploader } from '@/utils/upload.js'
  import { useRouter, useRoute } from 'vue-router';
  
  import { EluiChinaAreaDht } from 'elui-china-area-dht'
  const chinaData = new EluiChinaAreaDht.ChinaArea().chinaAreaflat

  const router = useRouter();
  const route = useRoute();
  // 查询参数
  const queryForm = reactive({
    kw: '',
    pageNo: 1,
    pageSize: 10
  });
  // 列表内容数量
  const total = ref(0);
  // 列表是否加载
  const loading = ref(true);
  // 列表返回值
  const list = ref<any[]>([]);
  const selectedCityOptions = ref<any[]>([]);
  const categoryList = ref<any[]>([
    {key: '背诵题', value: 1},{key: '赏析题', value: 2},
  ]);
  const optionList = ref<any[]>([
    'A', 'B', 'C', 'D'
  ]);
  
  // 表单实例
  const formRef = ref();
  // 是否打开弹出框
  const open = ref(false);
  const isEdit = ref(0);
  const openDetail = ref(false);
  // 弹出框标题
  const title = ref('');
  const detailData = ref();
  // 提交表单数据
  let editForm = toRef(
    reactive({
      id: '',
      poetryId: '',
      isActive: '1',
      content: '',
      optionA: '',
      optionB: '',
      optionC : '',
      optionD: '',
      correctAns: '',
    })
  );
  //多图上传的返回图片url数组
  const pics = ref<any>([])

  // 表单验证
  const rules = ref({
    questionType: [{ required: true, message: "请选择", trigger: "blur" }],
    poetryId: [{ required: true, message: "请输入", trigger: "blur" }],
    optionA: [{ required: true, message: "请输入", trigger: "blur" }],
    content: [{ required: true, message: "请输入", trigger: "blur" }],
    correctAns: [{ required: true, message: "请选择", trigger: "blur" }],
    optionB: [{ required: true, message: "请输入", trigger: "blur" }],
    optionC: [{ required: true, message: "请输入", trigger: "blur" }],
    optionD: [{ required: true, message: "请输入", trigger: "blur" }]
  });
  
  /**
   * 查询列表
   */
  const getList = () => {
    loading.value = true;
    baseService
      .post("/admin/question/list", queryForm).then((res) => {
        loading.value = false;
        if (res.code === 200) {
          list.value = res.data.records;
          total.value = res.data.totalrecord;
        } else {
          list.value = [];
        }
      })
      .catch(() => {
        loading.value = false;
      });
  };
  
  /**
   * 搜索按钮操作
   */
  function handleQuery() {
    queryForm.pageNo = 1;
    getList();
  }
  
  /**
   * 表单重置
   */
  function reset() {
    editForm.value = {
      id: '',
      poetryId: '',
      isActive: '1',
      content: '',
      optionA: '',
      optionB: '',
      optionC : '',
      optionD: '',
      correctAns: '',
    };
    selectedCityOptions.value = []
    pics.value = []
  
    nextTick(() => {
      formRef.value?.resetFields();
    });
  }
  
  /**
   * 新增按钮操作
   */
  function handleAdd() {
    reset();
    open.value = true;
    isEdit.value = 0;
    title.value = "添加";
    reset()
  }

  function showDetail(data){
    openDetail.value = true
    detailData.value = data
  }
  
  /**
   * 修改按钮操作
   * @param id 主键
   */
  function handleUpdate(id: string) {
    open.value = true;
    title.value = "修改";
    isEdit.value = 1;
    reset();
    baseService.get(`/admin/question/info/${id}`).then((res) => {
      if (res.code === 200) {
        editForm.value = res.data;
        pics.value = res.data.pics.split(',')
      }
    });
  }
  
  /**
   * 提交按钮
   */
  function submitForm() {
    formRef.value.validate((valid: boolean) => {
      if (!valid) return;
      console.log('图片字段', pics.value)
      // editForm.value.avatar = pics.value.join(',')
      baseService.post(`/admin/question/save`, editForm.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          // open.value = false;
          // getList();
          location.reload();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }
  
  /**
   * 删除按钮操作
   * @param id 主键
   */
  function handleDelete(id: any) {
    let msg = '确认要删除该题目吗?'
    ElMessageBox.confirm(msg, "提示").then(() => {
      baseService.get(`/admin/question/delete/${id}`).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }
  
  getList();
  </script>
  
<style scoped>
.price{
color: #F56C6C;
font-weight: bold;
}
.pointer{
    cursor: pointer;
}
.pointer:HOVER{
    color: #409eff;
}
.introduction{
  width: 80%;
  margin: 15px auto;
  white-space: pre-line;
}
.addpic{
  font-size: 22px;
  padding: 20px 25px 15px 25px;
  border: 2px dashed #ccc;
  color: #888;
  height: 68px;
}
.img-list{
  display: flex;
  flex-wrap: wrap;
}
.img-list .img-li{
  width: 260px;
  position: relative;
  margin-right: 10px;
}
.logo-remove{
  font-size: 22px;
  position: absolute;
  top: 10px;
  right: 10px;
  color: #f00;
  cursor: pointer;
  text-shadow: #000 4px 4px 5px;
}
.logo-remove .el-icon{
  box-shadow: #fff 3px 5px 6px;
  background-color: #fff;
}
.logo-remove:HOVER{
  color: #F56C6C;
}
</style>
  